import {
  Notification
} from 'element-ui';




/**
 * 混合了消息弹出框的函数
 */

function iNotify(title, type, msg) {
  Notification({
    title: title,
    message: msg,
    type: type
  });
};


function checkReg(type, data, msg) {
  var reg = '';
  if (type == 'phone') {
    reg = /^1[3456789]\d{9}$/;
  } else if (type == 'idCard') {
    reg = /^\d{6}(17|18|19|20|21|22)?\d{2}(0[1-9]|10|11|12)(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/i;
  }
  if (!reg.test(data)) {
    return false;
  } else {
    return true;
  }
};



const sCallBack = (res) => {

  if (res && res.solely_code == '100000') {
    iNotify(res.msg, 'success');
    return 'success';
  } else {
    iNotify(res.msg, 'error');
    return false;
  };

};


const timeToTimestamp = (format) => {

  var mydata = format.replace('-', '/');
  mydata = mydata.replace('-', '/');
  return new Date(mydata) / 1000;

};


const notify = (title, type, msg) => {

  Notification({
    title: title,
    message: msg,
    type: type ? type : 'success'
  });

};



const cloneForm = (form) => {

  var res = JSON.parse(JSON.stringify(form));
  return res;

};


const changeInt = (arr) => {
  var data = [];
  if(arr.length>0){
    arr.forEach((item,index)=>{
      data.push(parseInt(item))
    })
  }
  return data;
};



const timeto = (date, type, seper) => {
  if (seper) {
    var seperator1 = seper;
  } else {
    var seperator1 = '.';
  }
  var seperator2 = ":";
  var date = parseInt(date);


  var date = new Date(date);

  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  if (hours >= 0 && hours <= 9) {
    hours = "0" + hours;
  }
  if (minutes >= 0 && minutes <= 9) {
    minutes = "0" + minutes;
  }
  if (seconds >= 0 && seconds <= 9) {
    seconds = "0" + seconds;
  }
  if (type == "ym") {
    // 转年月
    var currentdate = date.getFullYear() + seperator1 + month;
  } else if (type == "ymd") {
    // 转年月日
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate;
  } else if (type == "md") {
    // 转月日
    var currentdate = month + seperator1 + strDate;
  } else if (type == "ymd-hm") {
    //转年月日 时分
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
      " " + hours + seperator2 + minutes;
  } else if (type == "ymd-hms") {
    //转年月日 时分秒
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
      " " + hours + seperator2 + minutes +
      seperator2 + seconds;
  } else if (type == "hms") {
    //转时分秒
    var currentdate = hours + seperator2 + minutes + seperator2 + seconds;
  } else if (type == "hm") {
    //转时分秒
    var currentdate = hours + seperator2 + minutes;
  }
  return currentdate;
};



const getMonth = (date) => {
  let inDate = new Date(date)
  let year = inDate.getFullYear()
  let month = inDate.getMonth()
  let startTime = new Date(year, month, 1).getTime()
  let endTime = new Date(year, month + 1, 1).getTime() - 1
  return [parseInt(startTime / 1000), parseInt(endTime / 1000)]
};



const imgchange = (self, data, formName, attrName) => {


  data.forEach((item, index) => {

    if (item['response']) {
      item['url'] = item['response'];
    };
    delete item['percentage'];
    delete item['raw'];
    delete item['size'];
    delete item['status'];
    delete item['response'];
    delete item['uid'];

  });


  if (data.length) {
    self[formName][attrName] = data;
  } else {
    self[formName][attrName] = 'empty';
  };

};



const resetForm = (formName) => {
  self.$refs[formName].resetFields();
  console.log('restform');
  if (formName == 'searchform') {
    self[formName] = {};
  }
};



function padLeftZero(str) {
  return ('00' + str).substr(str.length);
};



const formatDate = (date, fmt) => {

  if (!date || date == 'undefined' || date == 'null' || date == "Invalid Date") {
    return;
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }

  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  };
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
};



const getParentNames = (array, id, childName, results) => {

  if (!childName) {
    var childName = 'children';
  };

  if (!results) {
    var results = [id];
  };
  var pid = '';
  getParentId(array, id);

  if (pid) {
    results.push(pid);

    if (pid > 0) {
      getParentNames(array, pid, childName, results);
    }
  };
  return results;

  function getParentId(array, id) {

    for (var i = 0; i < array.length; i++) {
      if (pid > 0) {
        return false;
      };
      var item = array[i];
      if (item.id == id) {
        pid = item.parentid;
        return false;
      } else if (item[childName] && item[childName].length > 0) {
        getParentId(item[childName], id);
      };
    };
  };
};






const isArrayFn = (value) => {

  if (typeof Array.isArray === "function") {
    return Array.isArray(value);
  } else {
    return Object.prototype.toString.call(value) === "[object Array]";
  }

};



const isTest = (value) => {

  return value

};

const getBackRoute = (tabList, fullPath) => {

  var backRes = '';
  var newRes = {
    path: '/home/dashboard',
  };
  var backRouter = '';
  var newRouter = '';
  var backPath = '';


  if (fullPath) {
    for (var i = 0; i < tabList.length; i++) {
      if (fullPath == tabList[i].router) {
        backPath = tabList[i]['params']['backPath'];
        break;
      };
    };
  };


  if (backPath) {
    for (var i = 0; i < tabList.length; i++) {
      if (tabList[i].params && tabList[i].params['path']) {
        if (backPath == tabList[i].params['path']) {
          backRouter = tabList[i];
          break;
        };
      } else if (backPath == tabList[i].router) {
        backRouter = tabList[i];
        break;
      };
    };

    if (backRouter) {
      if (backRouter.params && backRouter.params['path']) {
        backRes = {
          path: backRouter.params['path'],
          name: backRouter.name,
          params: backRouter.params ? backRouter.params : {},
          query: backRouter.query ? backRouter.query : {},
        };

      } else {
        backRes = {
          path: backRouter.router,
          name: backRouter.name,
          params: backRouter.params ? backRouter.params : {},
          query: backRouter.query ? backRouter.query : {},
        };

      };
    } else {
      if (tabList.length > 0) {
        newRes = {
          path: tabList[0].router,
          name: tabList[0].name,
          params: tabList[0].params ? tabList[0].params : {},
          query: tabList[0].query ? tabList[0].query : {},
        };
      };
    };


  };

  return {
    backRes: backRes,
    newRes: newRes
  }

};



const getChildNames = (array, key, childName, id, results) => {

  if (!childName) {
    var childName = 'children';
  };

  if (!results) {
    var results = [];
  };
  var child_array = [];
  getChildrenArray(array, key);

  if (child_array.length > 0) {
    getChildId(child_array, key)
  };

  return results;

  function getChildrenArray(array, key) {
    for (var i = 0; i < array.length; i++) {
      if (array[i][key] == id) {
        if (array[i][childName] && array[i][childName].length > 0) {
          child_array = array[i][childName];
        }
      } else if (array[i][childName] && array[i][childName].length > 0) {
        getChildrenArray(array[i][childName], key);
      };
    };
  };

  function getChildId(child_array, key) {
    for (var i = 0; i < child_array.length; i++) {
      results.push(child_array[i][key]);
      if (child_array[i][childName] && child_array[i][childName].length > 0) {
        getChildId(child_array[i][childName], key);
      };
    };
  };
};


const getArrayByTarget = (array, targetName, target, childName) => {

  var results = [];
  if (!childName) {
    var childName = 'children'
  };

  getItemsBytarget(array, targetName, target, childName);

  return results;

  function getItemsBytarget(array, targetName, target, childName) {

    for (var i = 0; i < array.length; i++) {
      if (results.length > 0) {
        return false;
      };
      var item = array[i];
      if (item[targetName] == target) {
        results.push(item);
      } else if (item[childName] && item[childName].length > 0) {
        getItemsBytarget(item[childName], targetName, target, childName);
      }
    };

  };

};



const getArrayByTargetTwo = (array, targetName, target) => {

  var results = [];
  getItemsBytarget(array, targetName, target);
  return results;

  function getItemsBytarget(array, targetName, target) {

    for (var i = 0; i < array.length; i++) {
      if (results.length > 0) {
        return false;
      }
      var item = array[i];
      if (item[targetName] == target) {
        results.push(item);
      } else if (item.children && item.children.length > 0) {
        getItemsBytarget(item.children, targetName, target);
      }
    };

  };

};


const getArrToArrByParent = (array, resArr, keyName) => {

  var result = [];

  if (!childName) {
    var childName = 'children';
  };

  for (var i = 0; i < resArr.length; i++) {
    var oneResult = [];
    var hasOne = false;
    getParentArr(array, resArr[i]);
    if (oneResult.length > 0) {
      result.push(oneResult);
    }
  };


  return result;

  function getParentArr(array, key, res) {

    for (var j = 0; j < array.length; j++) {

      if (hasOne) {
        return;
      };

      if (!res) {
        var testRes = [];
      } else {
        var testRes = res.concat([])
      };

      testRes.push(array[j][keyName]);

      if (array[j][keyName] != key && array[j][childName] && array[j][childName].length > 0) {
        getParentArr(array[j][childName], key, testRes);
      } else if (array[j][keyName] == key) {
        oneResult = testRes;
        hasOne = true;
      };

    };

  };


}



export default {
  isArrayFn,
  getArrayByTarget,
  isTest,
  cloneForm,
  imgchange,
  resetForm,
  formatDate,
  getParentNames,
  sCallBack,
  notify,
  formatDate,
  getArrayByTargetTwo,
  getChildNames,
  timeto,
  timeToTimestamp,
  getArrToArrByParent,
  getBackRoute,
  checkReg,
  getMonth,
  changeInt
}